package com.runtime.hongyunmanage.controller;

import com.runtime.hongyunmanage.domain.Carousels;
import com.runtime.hongyunmanage.domain.vo.CarouselsVo;
import com.runtime.hongyunmanage.domain.vo.OrdersVo;
import com.runtime.hongyunmanage.service.CarouselsService;
import com.runtime.hongyunmanage.utils.UploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/Carousels")
public class CarouselsController {
    @Autowired
    private CarouselsService carouselsService;

    @GetMapping
    public List<Carousels> findAll() {
        List<Carousels> list= carouselsService.findAll();
        return  list;
    }

    @GetMapping("/lin")
    public Integer findLin() {
        return 66666;
    }

    @PostMapping("/updateSortOrder")
    public void swapSortOrder(@RequestBody CarouselsVo dto) {
        carouselsService.swapSortOrder(dto.getUpId(), dto.getDownId());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<String> delete(@PathVariable Integer id) {
        try {
            // 获取轮播图信息
            Carousels carousels = carouselsService.selectId(id);
            System.out.println(carousels);
            if (carousels != null) {
                // 获取图片路径
                String imageUrl = carousels.getImageUrl();
                System.out.println(imageUrl + 123456);
                if (imageUrl != null && !imageUrl.isEmpty()) {
                    // 去除路径中的"image"部分
                    String modifiedImageUrl = imageUrl.replace("image/", "");
                    System.out.println("Modified Image URL: " + modifiedImageUrl);

                    // 删除文件系统中的图片
                    deleteImageFile("static/image", modifiedImageUrl);
                    deleteImageFile("image", modifiedImageUrl);
                }
            }
            // 删除数据库中的记录
            int deleteCount = carouselsService.delete(id);
            if (deleteCount > 0) {
                return ResponseEntity.ok("删除成功");
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到记录");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("删除失败");
        }
    }

    private void deleteImageFile(String basePath, String relativePath) {
        String filePath = basePath + "/" + relativePath;
        File imageFile = new File(filePath);
        if (imageFile.exists() && imageFile.delete()) {
            System.out.println("文件删除成功: " + filePath);
        } else {
            System.out.println("文件删除失败或文件不存在: " + filePath);
        }
    }


    @PostMapping("/updateDetail")
    public int updateDetail(@RequestParam("id") Integer id,
                            @RequestParam(value = "file", required = false) MultipartFile file,
                            @RequestParam("description") String description,
                            @RequestParam("endAt") String endDate) {
        try {
            // 处理文件上传逻辑
            String imageUrl = null;
            if (file != null && !file.isEmpty()) {
                String uploadDir = "static/image";
                File uploadPath = new File(uploadDir);
                if (!uploadPath.exists()) {
                    uploadPath.mkdirs();
                }

                String randomFileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
                imageUrl = "image/" + randomFileName; // 保存图片的相对路径
                String filePath = uploadPath.getAbsolutePath() + File.separator + randomFileName;

                file.transferTo(new File(filePath));
            }

            // 如果没有上传新文件，获取原来的 imageUrl
            if (imageUrl == null || imageUrl.isEmpty()) {
                Carousels carousels = carouselsService.getById(id);
                if (carousels != null) {
                    imageUrl = carousels.getImageUrl();
                }
            }
            // 格式化 endDate
            String formattedEndDate;
            try {
                // 尝试解析 ISO_OFFSET_DATE_TIME 格式
                OffsetDateTime offsetDateTime = OffsetDateTime.parse(endDate);
                formattedEndDate = offsetDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            } catch (DateTimeParseException e) {
                // 如果解析失败，尝试解析 yyyy-MM-dd HH:mm:ss 格式
                LocalDateTime localDateTime = LocalDateTime.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                formattedEndDate = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }

            // 调用服务层更新方法
            return carouselsService.updateDetail(id, imageUrl, description, formattedEndDate);
        } catch (Exception e) {
            e.printStackTrace();
            return -2; // 返回错误代码
        }
    }

    @PostMapping("/img")
    public ResponseEntity<String> img(@RequestParam("file") MultipartFile file,
                                      @RequestParam("description") String description,
                                      @RequestParam("endAt") String endDate) throws IOException {
        // 指定一个外部目录来存储上传的文件
        String uploadDir = "static/image"; // 修改这里为您的上传目录
        File uploadPath = new File(uploadDir);
        if (!uploadPath.exists()) {
            uploadPath.mkdirs();
        }

        // 生成随机文件名
        String randomFileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        String filePath = uploadPath.getAbsolutePath() + File.separator + randomFileName;
        String filePathData = "image/" + randomFileName;

        String fileName = file.getOriginalFilename();
        UploadUtils.saveFileToJarPath(getClass(), fileName, file);
        // 保存文件
        file.transferTo(new File(filePath));
        // 将文件路径和描述信息存储到数据库
        int result = carouselsService.addImageByType(filePathData, description, endDate);
        // 将文件路径和描述信息存储到数据库
        if (result > 0) {

            return ResponseEntity.ok("图片上传成功，路径已存储到数据库");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("图片上传成功，但存储路径到数据库失败");
        }
    }
}


